<template>
  <div v-loading="loading" style="background-color:#fff;padding:10px;">
    <el-row>
      <p>问卷标题：<strong>{{editQuestion.title}}</strong></p>
    </el-row>
    <el-row class="paper-container">
      <section class="active pages-container">
        <div v-for="(page,index) of editQuestion.pages" class="paper-item" :class="{ 'active': selPage && selPage.id === page.id }" :key="page.id" @click="selectPage(page)">
          <span class="page-number">{{index+1}}</span>
          <div class="btn-close" @click.stop="btnDel(page.id)">×</div>
        </div>
        <div class="paper-item add-item" @click="createPage">
          <icon name="plus" scale="3"></icon>
        </div>
      </section>
    </el-row>
    <section v-if="selPage">
      <el-row>
        <el-col :span="10" style="border-right:1px solid #e4e4e4">
          <el-row style="">
            <CreationToolbar v-on:newSection="newSection"></CreationToolbar>
          </el-row>
          <el-row>
            <qa-view-controller v-for="section of selPage.sections"
                                :key="section.key"
                                :question="section"
                                v-on:move="move"
                                v-on:update="update"
                                v-on:edit="edit"
                                v-on:remove="remove"></qa-view-controller>
          </el-row>
        </el-col>
        <el-col :span="14">
          <qa-edit-controler v-if="editSection" :page="selPage" :question="editSection" v-on:newRefSection="newSection" :tacticsIndexes="tacticsIndexes" v-on:update="update"></qa-edit-controler>
        </el-col>
      </el-row>
    </section>
  </div>
</template>

<script>
  import {mapGetters,mapActions} from 'vuex'
  import errHandler from '@/assets/errHandler'
  import CreationToolbar from '@/components/qa/CreationToolbar'
  import QaViewController from "@/components/qa/view/index";
  import QaEditControler from "@/components/qa/edit/index";
  export default {
    name: "qa-edit",
    components:{
      QaEditControler,
      QaViewController,CreationToolbar
    },
    watch:{
    },
    data() {
      return {
        loading:false,
        editQuestion:{pages:[]},
        selPage:null,
        editSection:null,
        tactics:null
      }
    },
    computed:{
      editId(){
        return this.$route.params.id
      },
      ...mapGetters({

      }),
    },
    created(){
      //加载问卷
      this.loadQuestionniares(this.editId)
    },
    methods:{
      ...mapActions({
        fetch:'fetch'
      }),
      getTacticsIndexes(id){
        this.fetch({name:"getTacticsIndexes",data:{tacticsId:id}})
          .then(res=>{
            this.tacticsIndexes=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      btnDel(id){
        this.fetch({name:"deletePage",data:{id}})
          .then(res=>{
            if(res.errCode){
              this.$message({type:'error',message:res.errMsg})
            }else{
              let pageIndex = this.editQuestion.pages.findIndex(p=>p.id===id)
              let page = this.editQuestion.pages[pageIndex]
              this.editQuestion.pages.splice(pageIndex,1)
              if(this.selPage && this.selPage.id === page.id){
                if(this.editQuestion.pages.length>0)
                  this.selectPage(this.editQuestion.pages[0])
              }
            }
          })
          .catch(err=>{
            console.log(err)
            this.$message({type:'error',message:'服务器错误'})
          })
      },
      loadQuestionniares(id){//——————————————————————————————————————————————————————————————————————————————————————————————
        this.fetch({name:"getQuestionnaire",data:{id}})
          .then((res)=>{
            console.log('qa',res)
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              if(res.data.tacticsId){
                this.getTacticsIndexes(res.data.tacticsId)
              }else
                this.tacticsIndexes = null
              //this.editQuestion = res;
              if(!res.pages) res.pages = []
              res.pages.forEach((p)=>{
                //p.active = true
                if(p.metadata)
                  p.sections = JSON.parse(p.metadata)
                else
                  p.sections = []
              })
              this.editQuestion = res
              if(this.editQuestion.pages.length>0){
                this.selectPage(this.editQuestion.pages[0])
                //this.selPage = this.editQuestion.pages[0]
                //加载第一页
              }
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'error',message:"服务器错误"})
          })
      },
      selectPage(page){
        console.log(page)
        //设置当前页面
        this.selPage = page
        if(!page.keyIndex) page.keyIndex = 1
        if(!page.sections)
          page.sections=[]
        this.editSection=null
      },
      createPage(){
        console.log('创建页面')
        this.fetch({name:"createPage",data:{qaId:this.editId}})
          .then(res=>{
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              this.editQuestion.pages.push(res);
              this.selectPage(res)
              console.log(res)
            }
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      newSection(params){
        let section = {key:'k'+this.selPage.keyIndex++,type:params.type,topic:params.topic,...params.data}
        if(params.type==='checkbox'||params.type==='radio')
          section.options=[]
        if(params.isRef){
          section.isRef=true
          section.ref={
            counter:0,
          }
        }
        this.selPage.sections.push(section)
        //保存下
        if(!section.isRef)//如果是关联问题，先不保存，等主问题返回一起保存
          this.saveCurrPage()
      },
      saveCurrPage(){
        //this.selPage
        console.log(this.selPage)
        this.loading = true
        this.fetch({name:'updatePage',data:{id:this.selPage.id,title:'测试page',keyIndex:this.selPage.keyIndex,metadata:JSON.stringify(this.selPage.sections)},method:'post'})
          .then((res)=>{
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              //this.selPage
              console.log(res)
              if(res.metadata)
                res.sections = JSON.parse(res.metadata)
              else
                res.sections = []
              //设置到 editQuestion
              let tmpPageIndex = this.editQuestion.pages.findIndex(p=>p.id==res.id)
              this.editQuestion.pages[tmpPageIndex] = res
              this.selPage=res
              //清除编辑区域
              this.editSection = null
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'err',message:err})
          })
          .finally(()=>{
            this.loading=false
          })
      },
      //联机操作方法
      update(payload) {
        //保存 刷新
        this.saveCurrPage()
      },
      edit(value) {
        this.editSection = this.selPage.sections.find(q=>q.key === value.key)
      },
      move(payload) {
        //console.log(payload)//找到索引
        let index = this.selPage.sections.findIndex(s=>s.key === payload.question.key)
        if(payload.direction === 'up'){
          if(index <= 0 ) return
          this.moveItem(this.selPage.sections,index,index-1)
        }else{
          if(index >= this.selPage.sections.length-1 ) return
          this.moveItem(this.selPage.sections,index,index+1)
        }
        this.saveCurrPage()
      },
      remove(section){
        //找到指定的qustion索引
        let index = this.selPage.sections.findIndex(s=>s.key === section.key)
        if(index>=0) {
          //看下是否关联问题，需要检查是否被关联
          if(section.isRef){
            let refIndex = this.selPage.sections.findIndex(s=>{
              if(s.refs){
                return s.refs.findIndex(r=>{
                  return r.refs.findIndex(r2=>r2 === section.key)>=0? true:false
                }) >=0? true:false
              }
              return false
            })
            if(refIndex>=0){
              this.$message({type:'error',message:'被[ '+this.selPage.sections[refIndex].topic+"] 关联，不能删除"})
              return
            }
          }
          this.selPage.sections.splice(index, 1)
          this.saveCurrPage()
        }
      },
      moveItem(arr,index1,index2){
        arr[index1] = arr.splice(index2, 1, arr[index1])[0];
        return arr;
      }
    }
  }
</script>

<style lang="scss">
  .stop-running{
    vertical-align: middle;
    margin-left: 5px;
    padding-top: 5px;
    cursor: pointer;
  }
  .paper-container{
    padding-bottom: 20px;
    border-bottom: 1px solid #e4e4e4;
    .header{
      position: relative;
    }
    .pages-container{
      display: none;
      &.active{
        display: block;
      }
    }
    .paper-item{
      float: left;
      box-sizing: border-box;
      margin: 10px;
      position: relative;
      width: 60px;
      height: 60px;
      border: 1px solid darkgrey;
      cursor: pointer;

      &:hover{
        border: 1px solid #8391a5;
        transition: all .2s ease;
        box-shadow: grey 0 0 6px 0;
        .btn-close{
          display: inline;
        }
      }
      &.active{
        box-shadow: #4db3ff 0 0 6px 0;
      }
      .page-number{
        color: darkgrey;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        transition: all .2s ease;
        font-size: 3em;
      }
      .btn-close{
        display: none;
        position: absolute;
        background-color: #f56c6c;
        border-radius:10px;
        color:#fff;
        width:20px;
        height:20px;
        line-height: 18px;
        text-align: center;
        font-size: 20px;
        overflow: hidden;
        top:-10px;
        right:-10px;
        padding:0;
        opacity: 0.6;
        &:hover{
          opacity: 1;
        }
      }
      &.add-item{
        border: 1px dashed darkgrey;
        .fa-icon{
          fill: darkgrey;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          transition: all .2s ease;
        }
        &:hover{
          border: 1px solid #8391a5;
          .fa-icon{
            fill: #8391a5;
          }
        }
      }
    }
  }
  .button-container{
    text-align: right;
    clear: both;
    box-shadow: 0 -4px 5px -5px #333;
    margin-right: 10px;
    padding-top:10px;
    padding-right:10px;
    box-sizing: border-box;
  }
  .form-container{
    .form-item{
      height: 200px;
      width: 180px;
    }
  }
</style>
